package com.lin.lazybone.ui;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.lin.lazybone.R;
import com.lin.lazybone.adapter.CourierAdapter;
import com.lin.lazybone.adapter.DialogLVAdapter;
import com.lin.lazybone.application.BaseActivity;
import com.lin.lazybone.entity.CourierData;
import com.lin.lazybone.entity.DelType;
import com.lin.lazybone.utils.L;
import com.lin.lazybone.utils.StaticClass;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by mr.lin on 2017/10/20.
 */

public class CourierActivity extends BaseActivity implements View.OnClickListener
{

    private Button courier_scan;
    private ImageView et_name;
    private EditText et_number;
    private Button btn_get_courier;
    private ListView mListView;
    private CustomDialog dialog;
    private ListView dialog_listView;
    private List<DelType> mDelType;
    //保存快递类型
    private String name = "";

    private List<CourierData> mList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_courier);
        Toolbar toolbar = (Toolbar) findViewById(R.id.courier_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        initData();
        initView();
    }

    private void initData()
    {
        //初始化快递信息
        mDelType = new ArrayList<>();
        mDelType.add(new DelType("sf", R.mipmap.sf));
        mDelType.add(new DelType("sto", R.mipmap.sto));
        mDelType.add(new DelType("zto", R.mipmap.zto));
        mDelType.add(new DelType("ems", R.mipmap.ems));
        mDelType.add(new DelType("best", R.mipmap.best));
        mDelType.add(new DelType("yto", R.mipmap.yto));
        mDelType.add(new DelType("yunda", R.mipmap.yunda));
    }

    //初始化View
    private void initView()
    {
        courier_scan = (Button) findViewById(R.id.courier_scan);
        courier_scan.setOnClickListener(this);
        et_name = (ImageView) findViewById(R.id.et_name);
        et_name.setOnClickListener(this);
        et_number = (EditText) findViewById(R.id.et_number);
        btn_get_courier = (Button) findViewById(R.id.btn_get_courier);
        btn_get_courier.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.mListView);
        dialog = new CustomDialog(this, 0, 1000, R.layout.dialog_deltype,
                R.style.Theme_dialog, Gravity.BOTTOM, R.style.pop_anim_style);
        dialog_listView = (ListView) dialog.findViewById(R.id.dialog_listView);
        DialogLVAdapter adapter = new DialogLVAdapter(this, mDelType);
        dialog_listView.setAdapter(adapter);
        dialog_listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                DelType delType = mDelType.get(position);
                name = delType.getType();
                et_name.setBackgroundResource(delType.getImageID());
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_get_courier:
                /**
                 * 1.获取输入框的内容
                 * 2.判断是否为空
                 * 3.拿到数据去请求数据（Json）
                 * 4.解析Json
                 * 5.listview适配器
                 * 6.实体类（item）
                 * 7.设置数据/显示效果
                 */
                //隐藏虚拟键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                //1.获取输入框的内容
                String number = et_number.getText().toString().trim();

                //拼接我们的url
                String url = "http://v.juhe.cn/exp/index?key=" + StaticClass.COURIER_KEY
                        + "&com=" + name + "&no=" + number;

                //2.判断是否为空
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(number))
                {
                    //3.拿到数据去请求数据（Json）
                    RxVolley.get(url, new HttpCallback()
                    {
                        @Override
                        public void onSuccess(String t)
                        {
                            //Toast.makeText(CourierActivity.this, t, Toast.LENGTH_SHORT).show();
                            L.i("Courier:" + t);
                            //4.解析Json
                            parsingJson(t);
                        }
                    });
                } else
                {
                    Toast.makeText(this, "获取失败", Toast.LENGTH_SHORT).show();
                }
                break;

            //点击了快递类型图片
            case R.id.et_name:
                dialog.show();
                break;
            
            case R.id.courier_scan:
                Toast.makeText(this, "scan", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //解析数据
    private void parsingJson(String t)
    {
        mList.clear();
        try
        {
            JSONObject jsonObject = new JSONObject(t);
            JSONObject jsonResult = jsonObject.getJSONObject("result");
            JSONArray jsonArray = jsonResult.getJSONArray("list");
            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject json = (JSONObject) jsonArray.get(i);

                CourierData data = new CourierData();
                data.setRemark(json.getString("remark"));
                data.setZone(json.getString("zone"));
                data.setDatetime(json.getString("datetime"));
                mList.add(data);
            }
            //倒序
            Collections.reverse(mList);
            CourierAdapter adapter = new CourierAdapter(this, mList);
            mListView.setAdapter(adapter);
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    // 隐藏键盘
    private void hideKeyBoard()
    {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 得到InputMethodManager的实例
        if (imm.isActive())
        {
            // 如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);
            // 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
